package net.noday.demo.web;

import java.util.List;
import java.util.Map;

import net.noday.demo.domain.User;
import net.noday.demo.service.impl.UserServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user/reg.htm")
public class UserController {

//	private Logger logger =LoggerFactory.getLogger(UserController.class);
	@Autowired
	private UserServiceImpl userService;
	
	@RequestMapping(method=RequestMethod.POST)
	public ModelAndView addUser(@ModelAttribute("user")User user, 
			BindingResult result, SessionStatus status) {
//		logger.info("");
		new UserValidator().validate(user, result);
		if (result.hasErrors()) {
			return new ModelAndView("user/reg");
		} else {
			if (user.getUid() != 0) {
				userService.update(user);
			} else {
				userService.add(user);
			}
			status.setComplete();
			Map<String, Object> model = new ModelMap("message", "�����ɹ���5��󷵻�<a href=\"index.htm\">�������</a><input value=\"index.htm\" id=\"goto\" type=\"hidden\" />");
			return  new ModelAndView("redirect:../message.htm", model);
		}
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String getPage(@RequestParam(required=false,value="uid")String uid, ModelMap model) {
		User user = null;
		if (uid == null || "".equals(uid)) {
			user = new User();
		} else {
			try {
				user = userService.loadById(Integer.parseInt(uid));
			} catch (NumberFormatException e) {
				user = new User();
				e.printStackTrace();
			}
		}
		model.addAttribute("user", user);
		return "user/reg";
	}
	
	@ModelAttribute("group")
	public List<String> getGroup() {
		return null;
	}
	
	private static final class UserValidator implements Validator {

		@Override
		public boolean supports(Class<?> clazz) {
			return User.class.isAssignableFrom(clazz);
		}

		@Override
		public void validate(Object target, Errors errors) {
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "required");
			
		}
		
	}
}
